﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data.EntityClient;

namespace AppQlyNhaSach.Configuaration
{
    public partial class frmConfig : DevExpress.XtraEditors.XtraForm
    {
        public string CreateConnectionString(string server, string database, string uid, string pwd)
        {
            var csb = new SqlConnectionStringBuilder();
            csb.DataSource = server;
            csb.InitialCatalog = database;
            csb.UserID = uid;
            csb.Password = pwd;
            return csb.ToString();
        }

        public string CreateEntityConnectionString(string server, string database, string uid, string pwd)
        {
            var csb = new SqlConnectionStringBuilder();
            csb.DataSource = server;
            csb.InitialCatalog = database;
            csb.UserID = uid;
            csb.Password = pwd;

            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.Metadata = @"res://*/QlyNhaSach.csdl|res://*/QlyNhaSach.ssdl|res://*/QlyNhaSach.msl";
            entityBuilder.Provider = "System.Data.SqlClient";
            entityBuilder.ProviderConnectionString = csb.ToString();
            return entityBuilder.ToString();
        }

        private string CreateEntityConnectionString()
        {
            string server = txtServer.Text.Trim();
            string database = txtDatabase.Text.Trim();
            string uid = txtUser.Text.Trim();
            string pwd = txtPass.Text.Trim();
            return CreateEntityConnectionString(server, database, uid, pwd);
        }

        public frmConfig()
        {
            InitializeComponent();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string cnStr = CreateEntityConnectionString();
                // new SqlConnection(cnStr).Open();
                EntityConnection cn = new EntityConnection(cnStr);
                cn.Open();
                // Console.WriteLine("Just testing the connection.");
                cn.Close();
                Properties.Settings.Default.ConnectionStringUser = cnStr;
                if (chkSaveConfig.Checked)
                {
                    Properties.Settings.Default.Save();
                }
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Test results", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
    }
}